<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="">
            <el-input
              v-model="foodName"
              size="medium"
              placeholder="查询"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              type="success"
              @click="getRecord"
              icon="el-icon-search"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button
              size="small"
              type="primary"
              @click="newest(1)"
              icon="el-icon-circle-plus-outline"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
        <div>
          <el-table
            :data="tableData"
            border
            v-loading="loadFlag"
            style="width: 100%"
          >
            <el-table-column
              prop="orderNumber"
              label="订单编号"
              width=""
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="purchaseDate"
              label="采购日期"
              width=""
              align="center"
            >
            </el-table-column>
            <el-table-column prop="buyer" label="采购员" align="center">
            </el-table-column>

            <el-table-column prop="purpose" label="用途" align="center">
            </el-table-column>
            <el-table-column prop="projectNumber" label="项目编号">
            </el-table-column>
            <el-table-column label="进度" align="center">
              <template #default="scope">
                <el-tag type="warning" v-if="scope.row.flowState == 0"
                  >进行中</el-tag
                >
                <el-tag type="success" v-if="scope.row.flowState == 1"
                  >已完成</el-tag
                >
                <el-tag type="danger" v-if="scope.row.flowState == 2"
                  >驳回</el-tag
                >
                <el-tag type="danger" v-if="scope.row.flowState == 3"
                  >不同意</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" align="center">
            </el-table-column>
            <el-table-column label="操作" width="220" align="center">
              <template #default="scope">
                <el-button
                  size="mini"
                  type="success"
                  v-if="scope.row.isCanApproval == 1"
                  @click="examine(scope.row, 3)"
                  >审核</el-button
                >
                <el-button size="mini" @click="editorPara(scope.row, 2)"
                  >查看</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="pagingClass">
            <el-pagination
              :page-sizes="m_page.sizes"
              :page-size="m_page.size"
              :current-page="m_page.number"
              @size-change="m_handleSizeChange"
              @current-change="m_handlePageChange"
              layout="total,sizes,prev, pager, next"
              background
              :total="m_page.totalElements"
            ></el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      :title="single"
      v-model="plassets"
      width="1050px"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :inline="true" :model="form" label-width="100px">
        <el-form-item label="订单编号">
          <el-input style="width: 300px" v-model="form.orders"></el-input>
        </el-form-item>
        <el-form-item label="采购日期">
          <el-date-picker
            style="width: 300px"
            v-model="form.dates"
            type="date"
            placeholder="选择日期"
            format="YYYY 年 MM 月 DD 日"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购员">
          <el-select
            v-model="form.buyer"
            style="width: 300px"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in subbuyer"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio v-model="form.department" :label="1">个人采购</el-radio>
          <el-radio v-model="form.department" :label="2">公司采购</el-radio>
        </el-form-item>

        <el-form-item label="用途">
          <el-input style="width: 300px" v-model="form.usemasks"></el-input>
        </el-form-item>
        <el-form-item label="项目编号">
          <el-input
            :disabled="true"
            style="width: 300px"
            v-model="form.numbers"
          ></el-input>
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="subitem()"
          ></el-button>
        </el-form-item>
        <el-form-item label="采购单明细" style="width: 1100px">
          <el-button type="success" plain @click="addLine">新增</el-button>
          <el-table
            :data="procurement"
            show-summary
            border
            style="width: 900px"
          >
            <el-table-column label="产品名称" width="250">
              <template #default="scope">
                <el-input
                  style="width: 180px"
                  v-model="scope.row.productName"
                  placeholder="名称"
                ></el-input>
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="get_product(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column label="供应商" width="200">
              <template #default="scope">
                <el-select
                  v-model="scope.row.supplierId"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in SupplierDetails"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="产品规格" width="100">
              <template #default="scope">
                <el-input v-model="scope.row.productSpecifications"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="单位" width="100">
              <template #default="scope">
                <el-input v-model="scope.row.unit"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="addnote" label="图片" width="200">
              <el-upload
                style="width: 200px"
                action="https://jsonplaceholder.typicode.com/posts/"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-table-column>
            <el-table-column label="单价" width="140">
              <template #default="scope">
                <el-input
                  type="number"
                  v-model.number="scope.row.price"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="130">
              <template #default="scope">
                <el-input
                  type="number"
                  v-model.number="scope.row.number"
                  @input="hello(scope.row, scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="金额小计" width="130">
              <template #default="scope">
                <el-input
                  :disabled="true"
                  type="number"
                  v-model.number="scope.row.subtotal"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="deleteunused(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :rows="2"
            style="width: 300px"
            placeholder="请输入内容"
            v-model="form.newnotes"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="图片" style="width: 300px"> </el-form-item>
        <el-form-item label="审批进度" style="width: 300px" v-if="under == 2">
          <div style="height: 300px; margin-left: 30px">
            <el-steps
              direction="vertical"
              :active="stripes"
              v-if="passive.length"
            >
              <el-step
                v-for="item in passive"
                :title="item.nodeName"
                :key="item.id"
              ></el-step>
            </el-steps>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="plassets = false">取 消</el-button>
          <el-button type="primary" v-if="under == 1" @click="determine()"
            >确 定</el-button
          >
          <el-button @click="hardware()" v-if="under == 2" type="primary"
            >编辑 确 定</el-button
          >
          <el-button type="success" @click="Disagree()" v-if="under == 3"
            >同意</el-button
          >
          <el-button type="danger" @click="RefuseSet()" v-if="under == 3"
            >拒绝</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="选择产品"
      v-model="Selectors"
      width="800px"
      :close-on-click-modal="false"
    >
      <commodity
        @saveCalendar="saveCalendar"
        @closeCalendar="canceloff"
      ></commodity>
    </el-dialog>
    <el-dialog
      title="选择项目编号"
      v-model="nserialnos"
      width="800px"
      :close-on-click-modal="false"
    >
      <getProject @wtc_serial="wtc_serial"></getProject>
    </el-dialog>
  </div>
</template>

<script>
import commodity from "@/components/commodity";
import getProject from "./myProject/getProject";
import dayjs from "dayjs";
export default {
  components: {
    commodity,
    getProject,
  },
  data() {
    return {
      loadFlag: false, //加载flag
      foodName: "",
      addProduct: "",
      procurement: [
        {
          id: 0,
          productName: "", //产品名称
          supplierId: "", //供应商
          // productNumber: "", //产品编号
          productSpecifications: "", //产品规格
          // warehouseId: "", //仓库
          unit: "", //单位
          price: "", //产品单价
          number: "", //数量
          subtotal: "", //小计
          file: "", //图片
        },
      ],
      SupplierDetails: [],
      dialogImageUrl: "",
      dialogVisible: false, //上传图片
      form: {
        orders: "",
        dates: "",
        buyer: "", //采购员
        department: "",
        fname: "",
        usemasks: "", //用途
        numbers: "", //编号
        numbersID: "", //编号ID
        newnotes: "",
      },
      subbuyer: [], //人员
      passive: [],
      plassets: false,
      Selectors: false,
      nserialnos: false,
      single: "",
      under: 1,
      headerObj: "", //请求头
      tableData: [],
      underID: "",
      m_page: {
        sizes: [10, 20, 40, 50, 100], //每页最大显示数
        size: 10,
        totalElements: 0,
        totalPages: 3,
        number: 1,
      },
      paging: {
        sizes: [10, 20, 40, 50, 100], //每页最大显示数
        size: 10,
        totalElements: 0,
        totalPages: 3,
        number: 1,
      },
      className: [],
      deviceDetails: [],
      stripes: "",
      ApprovalHistoryJson: [],
      approvers: {
        approvalIds: "",
        approvalState: "",
        approvalers: "",
        createId: "",
        createTime: "",
        id: "",
        isEffective: "",
        nodeName: "",
        nodeType: "",
        pId: "",
        processdesigndetailsId: "",
        sort: "",
        tableName: "",
        updateTime: "",
      },
      csListIndex: null,
    };
  },
  created() {
    let str = sessionStorage.getItem("token");
    this.headerObj = `Bearer ${str}`;
  },
  beforeMount() {
    this.production();
    this.getsuppliers();
    this.getRecord(); //获取数据
  },
  methods: {
    hello(row) {
      if (row.number) {
        row.subtotal = row.price * row.number;
        console.log(row.subtotal);
      }
    },
    subitem() {
      this.nserialnos = true;
    },
    wtc_serial(data) {
      this.form.numbers = data.serialNumber;
      this.numbersID = data.id;
      this.nserialnos = false;
    },
    //拒绝
    RefuseSet() {},
    //同意
    Disagree() {
      this.$axios
        .post(
          `api/serial/ApprovalHistory`,
          {
            pId: this.underID,
            nodeName: this.approvers.nodeName,
            tableName: this.approvers.tableName,
            nodeType: this.approvers.nodeType,
            approvalIds: this.approvers.approvalIds,
            isEffective: this.approvers.isEffective,
            processdesigndetailsId: this.approvers.processdesigndetailsId,
            approvalState: 1,
            approvalers: this.approvers.approvalers,
            sort: this.approvers.sort,
            id: this.approvers.id,
          },
          {
            headers: {
              Authorization: this.headerObj,
            },
          }
        )
        .then(() => {
          this.$message({
            message: "同意",
            type: "success",
          });
          this.getRecord();
          this.plassets = false;
        });
    },
    //审核
    examine(row, index) {
      this.under = index;
      this.underID = row.id;
      this.form.numbers = row.projectNumber;
      this.single = "审核";
      this.plassets = true;
      this.$axios({
        methods: "GET",
        url: "api/serial/Purchase",
        headers: {
          Authorization: this.headerObj,
        },
        params: {
          query: {
            id: this.underID,
          },
        },
      }).then((res) => {
        // console.log(res);
        this.fontify = res.data.data[0];
        console.log(this.fontify);
        this.form.orders = this.fontify.orderNumber;
        this.form.dates = this.fontify.purchaseDate;
        this.form.buyer = this.fontify.buyerId; //审核员
        this.form.department = this.fontify.type;
        // this.form.supplier = this.fontify.supplierId; //供应商
        this.form.usemasks = this.fontify.purpose;
        this.form.numbersID = this.fontify.projectId;
        this.procurement = this.fontify.purchaseDetails;
        this.form.newnotes = this.fontify.remarks;
        this.getProcess();
      });
    },
    //获取流程
    getProcess() {
      this.$axios({
        methods: "GET",
        url: "api/serial/ApprovalHistory",
        headers: {
          Authorization: this.headerObj,
        },
        params: {
          pageSize: 20,
          pageIndex: 1,
          query: {
            pId: this.underID,
            tableName: "purchase",
          },
        },
      })
        .then((res) => {
          // console.log(res);
          // this.ApprovalHistoryJson = res.data.data;
          // console.log(this.ApprovalHistoryJson);
          this.approvers = res.data.data[1];
          console.log(this.approvers);
          this.passive = res.data.data;
          // console.log(this.passive);
          let term = this.passive.reduce((count, item) => {
            console.log(item);
            if (item.approvalState == 1 || item.approvalState == 3) {
              return count + 1;
            }
            return count;
          }, 0);
          this.stripes = term;
        })
        .catch(() => {
          this.$message.error("获取失败");
        });
    },
    //删除
    handleDelete(row) {
      let into = row;
      console.log(into);
      this.$confirm("确认删除该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post(
              `api/serial/Purchase`,
              {
                id: into.id,
                orderNumber: into.orderNumber, //订单编号
                purchaseDate: into.purchaseDate, //采购日期
                buyerId: into.buyerId, //采购员
                type: into.type, //类型
                // supplierId: 0, //供应商
                purpose: into.purpose, //用途
                projectId: into.projectId, //项目编号
                purchaseDetails: [],
                remarks: into.remarks, //备注s
                file: "", //图片
                isDelete: 1,
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              // console.log(res);
              this.getRecord();
              this.$message.success("删除成功");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑确定
    hardware() {
      this.$axios
        .post(
          `api/serial/Purchase`,
          {
            id: this.underID,
            orderNumber: this.form.orders, //订单编号
            purchaseDate: dayjs(this.form.dates).format("YYYY-M-D"), //采购日期
            buyerId: this.form.buyer, //采购员
            type: this.form.department, //类型
            // supplierId: 0, //供应商
            purpose: this.form.usemasks, //用途
            projectId: this.form.numbersID, //项目编号
            purchaseDetails: this.procurement,
            remarks: this.form.newnotes, //备注s
            file: "", //图片
          },
          {
            headers: {
              Authorization: this.headerObj,
            },
          }
        )
        .then(() => {
          // console.log(res);
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          this.plassets = false;
          this.getRecord();
          this.notEmpty();
        })
        .catch(() => {
          this.$message.error("编辑失败");
        });
    },
    //编辑
    editorPara(row, index) {
      // console.log(row);
      // console.log(index);
      this.passive = [];
      this.form.numbers = row.projectNumber;
      this.under = index;
      this.underID = row.id;
      this.single = "编辑采购";
      this.plassets = true;
      this.getProcess();
      this.$axios({
        methods: "GET",
        url: "api/serial/Purchase",
        headers: {
          Authorization: this.headerObj,
        },
        params: {
          query: {
            id: this.underID,
          },
        },
      }).then((res) => {
        // console.log(res);
        this.fontify = res.data.data[0];
        // console.log(this.fontify);
        this.form.orders = this.fontify.orderNumber;
        this.form.dates = this.fontify.purchaseDate;
        this.form.buyer = this.fontify.buyerId; //审核员
        this.form.department = this.fontify.type;
        // this.form.supplier = this.fontify.supplierId; //供应商
        this.form.usemasks = this.fontify.purpose;
        this.form.numbersID = this.fontify.projectId;
        this.procurement = this.fontify.purchaseDetails;
        this.form.newnotes = this.fontify.remarks;
      });
    },
    //新增
    determine() {
      this.$axios
        .post(
          `api/serial/Purchase`,
          {
            orderNumber: this.form.orders, //订单编号
            purchaseDate: dayjs(this.form.dates).format("YYYY-M-D"), //采购日期
            buyerId: this.form.buyer, //采购员
            type: this.form.department, //类型
            purpose: this.form.usemasks, //用途
            projectId: this.numbersID, //项目编号
            purchaseDetails: this.procurement,
            remarks: this.form.newnotes, //备注s
            file: "", //图片
          },
          {
            headers: {
              Authorization: this.headerObj,
            },
          }
        )
        .then(() => {
          // console.log(res);
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.plassets = false;
          this.getRecord();
          this.notEmpty();
        })
        .catch(() => {
          this.$message.error("保存失败");
        });
    },
    // 新增按钮
    newest(index) {
      this.under = index;
      this.single = "新增采购";
      this.plassets = true;
      this.notEmpty();
    },
    notEmpty() {
      this.form.orders = "";
      this.form.dates = "";
      this.form.buyer = "";
      this.form.department = 1;
      this.form.usemasks = "";
      this.form.numbers = "";
      this.form.newnotes = "";
      this.procurement.forEach((item) => {
        item.id = 0;
        item.productName = ""; //产品名称
        item.supplierId = ""; //供应商
        item.productSpecifications = ""; //产品规格
        item.unit = ""; //单位
        item.price = ""; //产品单价
        item.number = ""; //数量
        item.subtotal = ""; //小计
        item.file = ""; //图片
      });
    },
    full_name(row) {
      console.log(row);
    },
    //获取数据
    getRecord() {
      this.loadFlag = true;
      this.$axios({
        methods: "GET",
        url: "api/serial/Purchase",
        headers: {
          Authorization: this.headerObj,
        },
        params: {
          pageSize: this.m_page.size,
          pageIndex: this.m_page.number,
          query: {
            buyer: this.foodName,
          },
        },
      }).then((res) => {
        //  count: this.m_page.totalElements
        ({ data: this.tableData, count: this.m_page.totalElements } = res.data);
        // this.tableData.forEach((item) => {
        //   item.startDate = dayjs(item.startDate).format("YYYY-M-D");
        // });
        this.loadFlag = false;
      });
    },

    //获取产品
    get_product(index) {
      this.Selectors = true;
      this.csListIndex = index;
      // console.log(this.csListIndex);
      this.$nextTick(() => {
        // this.$refs.child.getProducts();
        // console.log(this.$refs.child);
      });
    },
    saveCalendar(data) {
      console.log(data);
      let parm = data;
      this.procurement[this.csListIndex].id = parm.id;
      this.procurement[this.csListIndex].productName = parm.productName;
      this.procurement[this.csListIndex].productNumber = parm.productNumber;
      this.procurement[this.csListIndex].productSpecifications =
        parm.productSpecifications;
      this.procurement[this.csListIndex].warehouseId = parm.warehouseId;
      this.procurement[this.csListIndex].unit = parm.unit;
      this.procurement[this.csListIndex].price = parm.unitPrice;

      this.procurement[this.csListIndex].file = parm.file;
      this.Selectors = false;
    },

    canceloff(data) {
      this.Selectors = data;
    },
    handleCurrentChange(val) {
      console.log(val);
      let flour = val;
      this.procurement[this.csListIndex].id = flour.id;
      this.procurement[this.csListIndex].productName = flour.productName;
      this.procurement[this.csListIndex].productNumber = flour.productNumber;
      this.procurement[this.csListIndex].productSpecifications =
        flour.productSpecifications;
      // this.procurement[this.csListIndex].category = flour.productCategory;
      this.procurement[this.csListIndex].warehouseId = flour.warehouseId;
      this.procurement[this.csListIndex].unit = flour.unit;
      this.procurement[this.csListIndex].price = flour.unitPrice;
      this.procurement[this.csListIndex].file = flour.file;
      this.Selectors = false;
    },

    //获取供应商
    getsuppliers() {
      this.$axios
        .get(`api/serial/Supplier?pageSize=${100}&pageIndex=${1}`, {
          headers: {
            Authorization: this.headerObj,
          },
        })
        .then((res) => {
          this.choose = res.data.data;

          this.choose.forEach((item) => {
            this.SupplierDetails.push({
              value: item.id,
              label: item.supplierName,
            });
          });
        });
    },
    //获取人员
    production() {
      this.$axios
        .get(`api/serial/Users?pageSize=${100}&pageIndex=${1}`, {
          headers: {
            Authorization: this.headerObj,
          },
        })
        .then((res) => {
          this.dateEnd = res.data.data;
          let fwork = [];
          this.dateEnd.forEach((item) => {
            fwork.push({
              value: item.id,
              label: item.name,
            });
          });
          // console.log(fwork);
          this.subbuyer = fwork;
        });
    },
    //页码
    m_handlePageChange(currPage) {
      this.m_page.number = currPage;
      this.getRecord();
    },
    m_handleSizeChange(currSize) {
      this.m_page.size = currSize;
      this.getRecord();
    },

    //新增行数
    addLine() {
      var newValue = {
        id: 0,
        productName: "", //产品名称
        supplierId: "", //供应商
        // productNumber: "", //产品编号
        productSpecifications: "", //产品规格
        // warehouseId: "", //仓库
        unit: "", //单位
        price: "", //产品单价
        number: "", //数量
        subtotal: "", //小计
        file: "", //图片
      };
      this.procurement.push(newValue);
    },
    save() {
      //这部分应该是保存提交你添加的内容
      console.log(JSON.stringify(this.procurement));
    },
    deleteunused(index) {
      //删除行数
      console.log(index);
      this.procurement.splice(index, 1);
    },
    jednoho() {
      this.Sinnohsk = true;
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style scoped>
.addccc {
  margin-bottom: 20px;
}
.el-upload--picture-card {
  width: 100px;
  height: 100px;
}
.el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.avatar {
  width: 100px;
  height: 100px;
}
</style>